from datetime import datetime

from PyQt6.QtCore import Qt
from PyQt6.QtGui import QIcon, QPixmap
from PyQt6.QtWidgets import QMainWindow, QMessageBox

import appvar
import netshop as netshop
from ui.ConfirmShop_ui import Ui_MainWindow


class ConfirmShop(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(ConfirmShop, self).__init__()
        self.setupUi(self)
        self.setWindowIcon(QIcon('image/netshop.jpg'))
        self.setWindowFlag(Qt.WindowType.MSWindowsFixedSizeDialogHint)
        # 当前订单
        self.cart = []
        self.display_index = 0
        self.cur_oid = 0
        self.cur_total = 0.00
        # ui
        self.pbCfm.clicked.connect(self.cfmShop)
        self.pbCcl.clicked.connect(self.cancel)
        self.sbCNum.valueChanged.connect(self.changeCNum)
        self.pbBack.clicked.connect(self.backward)
        self.pbFor.clicked.connect(self.forward)
        self.pbPay.clicked.connect(self.payOrder)
        self.lbUsr.setText(appvar.getID())
        self.loadShop()

    def loadShop(self):
        """
        加载已选购商品
        """
        self.cart = []
        row = netshop.query_first('订单表', 1, appvar.getID(), (3, None))
        if row is None:
            return
        self.cur_oid = row['订单号']
        if row['支付金额（元）'] is not None:
            self.cur_total = row['支付金额（元）']
        # 查询商品记录
        for orderitem in netshop.query('订单项表', 0, self.cur_oid):
            dict_shop = {
                '商品号': orderitem['商品号'],
                '数量': int(orderitem['订货数量']),
                '状态': orderitem['状态']}
            commodity = netshop.query_first('商品表', 0, orderitem['商品号'])
            dict_shop['商品名称'] = commodity['商品名称']
            dict_shop['类别编号'] = commodity['类别编号']
            dict_shop['价格'] = commodity['价格']
            self.cart.append(dict_shop)
        # 显示数据
        if len(self.cart) > 0:
            self.showCart()

    def showCart(self):
        """
        显示数据
        """
        self.lbPName.setText(self.cart[self.display_index]['商品名称'])
        self.lbTCode.setText(self.cart[self.display_index]['类别编号'])
        self.lbPPrice.setText(str(self.cart[self.display_index]['价格']))
        self.sbCNum.setValue(self.cart[self.display_index]['数量'])
        image = QPixmap('image/%s.jpg' % self.cart[self.display_index]['商品号'])
        self.lbImg.setPixmap(image)
        if self.cart[self.display_index]['状态'] == '订购':
            self.lbStatus.setText('已订购')
            self.pbCfm.setEnabled(False)
            self.pbCcl.setEnabled(True)
        else:
            self.lbStatus.setText('')
            self.pbCfm.setEnabled(True)
            self.pbCcl.setEnabled(False)
        self.lbTotal.setText('%.2f' % self.cur_total)

    def cfmShop(self):
        """
        订购商品
        """
        # 计算金额
        pid = self.cart[self.display_index]['商品号']
        cnum = self.sbCNum.value()
        pay = self.cart[self.display_index]['价格'] * cnum
        # 修改 Excel 表
        item = netshop.query_first('订单项表', 0, self.cur_oid, (1, pid))
        netshop.update_cells('订单项表', {
            'C%d' % (item['_row'] + 1): cnum,
            'D%d' % (item['_row'] + 1): '订购'})
        item = netshop.query_first('订单表', 0, self.cur_oid)
        netshop.update_cells('订单表', {
            'C%d' % (item['_row'] + 1): self.cur_total + pay,
            'alignments': ['C%d' % (item['_row'] + 1)]})
        self.loadShop()

    def cancel(self):
        """
        取消订阅
        """
        pid = self.cart[self.display_index]['商品号']
        cnum = self.cart[self.display_index]['数量']
        pay = self.cart[self.display_index]['价格'] * cnum
        item = netshop.query_first('订单项表', 0, self.cur_oid, (1, pid))
        netshop.update_cells('订单项表', {
            'C%d' % (item['_row'] + 1): 1,
            'D%d' % (item['_row'] + 1): '选购'
        })
        item = netshop.query_first('订单表', 0, self.cur_oid)
        netshop.update_cells('订单表', {
            'C%d' % (item['_row'] + 1): self.cur_total - pay,
            'alignments': ['C%d' % (item['_row'] + 1)]
        })
        self.loadShop()

    def backward(self):
        """
        上一页
        """
        if len(self.cart) == 0:
            pass
        elif self.display_index > 0:
            self.display_index -= 1
            self.showCart()
        else:
            self.display_index = len(self.cart) - 1
            self.showCart()

    def forward(self):
        """
        下一页
        """
        if len(self.cart) == 0:
            pass
        elif self.display_index < len(self.cart) - 1:
            self.display_index += 1
            self.showCart()
        else:
            self.display_index = 0
            self.showCart()

    def payOrder(self):
        """
        结算
        """
        # 修改订单项表
        values = {}
        for item in netshop.query('订单项表', 0, self.cur_oid):
            if item['状态'] == '订购':
                values['D%d' % (item['_row'] + 1)] = '结算'
        netshop.update_cells('订单项表', values)
        # 修改订单表
        item = netshop.query_first('订单表', 0, self.cur_oid)
        netshop.update_cells('订单表', {
            'D%d' % (item['_row'] + 1): datetime.strftime(datetime.now(), '%Y.%m.%d %H:%M:%S'),
            'alignments': ['D%d' % (item['_row'] + 1)]
        })
        # 修改商品表
        values = {}
        for item in self.cart:
            p = netshop.query_first('商品表', 0, item['商品号'])
            values['E%d' % (p['_row'] + 1)] = p['库存量'] - item['数量']
        netshop.update_cells('商品表', values)
        # 下单成功
        QMessageBox.information(self, '提示', '下单成功!')
        self.close()

    def changeCNum(self, num):
        """
        变更个数
        """
        # 检查数量是否足够
        pid = self.cart[self.display_index]['商品号']
        item = netshop.query_first('商品表', 0, pid)
        max_count = item['库存量']
        if num > max_count:
            self.sbCNum.setValue(max_count)
            return
        # 修改已订购商品
        status = self.cart[self.display_index]['状态']
        if status == '订购':
            price = self.cart[self.display_index]['价格']
            cnum_old = self.cart[self.display_index]['数量']
            self.cur_total = self.cur_total - price * cnum_old + price * num
            # 修改价格
            item = netshop.query_first('订单项表', 0, self.cur_oid, (1, pid))
            netshop.update_cells('订单项表', {
                'C%d' % (item['_row'] + 1): num,
            })
            item = netshop.query_first('订单表', 0, self.cur_oid)
            netshop.update_cells('订单表', {
                'C%d' % (item['_row'] + 1): self.cur_total,
                'alignments': ['C%d' % (item['_row'] + 1)]
            })
            self.loadShop()
